import PagePromoterUtil, { PagePromoter } from '../../../data/common/pagePromoter';
import AppSceneUtil from '../../../data/common/appScene';
import create from '../../../utils/create2.js'
import store from '../../../store/index.js'
import SessionUtil, {JxbHttpClient} from "../../../data/session/session"
import SystemUtil from '../../../shell/system/system';
create(store, {
  /**
   * 页面的初始数据
   * tagId：单页id
   * tagType_list：单页内容
   * imageSize：图片高度
   */
  data: {
    tagId: 0,
    list: [],
    imageSize: [],
    filters: [],
    pageSize: 10,
    pageNo: 0,
    load: false,
    tips: '加载更多',
    type: 'lower',
    keywords: '',
    coupon: {},
    latitude: '',
    longitude:'',
    isCoupon: false //品鉴券页面标识
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getApp().getSaleMode()
    // 开启转发按钮
    PagePromoterUtil.showShareMenu(true).then()
    SessionUtil.getInstance().then(session => {
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this)
      wx.setNavigationBarTitle({
        title: "餐厅列表"
      })
      const {id, from} = options
      if (id) {
        this.setData({
          tagId: id
        });
      }
      if(from === 'coupon'){ // from = coupon 品鉴券页面
        this.setData({
          isCoupon : true
        })
      }else if(from){ // 餐厅筛选页面过来
        this.setData({
          tagId: this.store.data.moduleId
        })
      }
      wx.getLocation({
        complete: (res) => {
          const { latitude, longitude} = res
          this.setData({
            latitude: latitude ? latitude : '',
            longitude: longitude ? longitude: ''
          })
          this.getDinnerList();
        }
      })
      this.getFilterParams()
      this.filter = this.selectComponent('#filter')
      this.scroller = this.selectComponent('#scroller')
    })
  },
  onShow: function () {
    SessionUtil.getInstance().then(session=>{
      // 注册当前页面的场景信息
      AppSceneUtil.setPageScene(this, false)
      this.w_widths();
    })
  },
  /**
   * 获取餐厅筛选条件
   */
  getFilterParams() {
    (new JxbHttpClient()).request('AppMaster/DinnerRoom/dinnerAttribute')
        .then(jxbResp => {
          this.setData({
            filters: jxbResp.data,
          });
        })
  },
  /**
   * 获取餐厅列表
   */
  getDinnerList(keywords = '', params = '') {
    let page = this;
    const { isCoupon, latitude, longitude} = page.data
    const {coupon} = this.store.data
    let { pageNo, list, type } = page.data
    if (pageNo < 0) {
      this.setData({
        load: false,
        tips: '没有更多了'
      })
      return
    }
    if (type === 'upper') {
      this.scroller.showLoading()
    } else {
     pageNo += 1
    }
    let api, requestData
    if(isCoupon){
      api = '/AppMaster/BookDinner/getDinnerList'
      requestData = {
        dinner_coupon_id: coupon.dinner_coupon_id,
        keywords,
        latitude,
        longitude,
        attribute_value_ids: params,
        pageSize: page.data.pageSize,
        pageNo: pageNo
      }
    }else{
      api = '/AppMaster/PosSinglePage/getDinnerList'
      requestData = {
        module_id: page.data.tagId,
        keywords,
        latitude,
        longitude,
        attribute_value_ids: params,
        pageSize: page.data.pageSize,
        pageNo: pageNo
      }
    }
    (new JxbHttpClient()).request({
      url:api,
      data: requestData
    }).then(jxbResp => {
      let newList = jxbResp.data
      this.scroller.hideLoading()
      page.setData({
        list: pageNo > 1 ? list.concat(newList) : newList,
        load: false,
        tips: newList.length < 10 ? '没有更多了' : '加载更多',
        pageNo: newList.length < 10 ? -1 : pageNo
      });
    })
  },
  /**
   * 获取屏幕宽度
   */
  w_widths: function () {
    this.setData({
      w_width: SystemUtil.getSystemInfo(false).windowWidth,
    })
  },

  /**
   * 计算图片高度
   */
  imageLoad(e) {
    const data = e.currentTarget.id.split("_");
    const index = data[1];
    const $width = e.detail.width;   //获取图片真实宽度
    const $height = e.detail.height;
    const ratio = $width / $height;   //图片的真实宽高比例
    const viewWidth = this.data.w_width;   //设置图片显示宽度
    const viewHeight = viewWidth / ratio;    //计算的高度值
    const imageHeight = this.data.imageSize;
    imageHeight[index] = viewHeight - 80;
    this.setData({
      imageSize: imageHeight
    })
  },
  /**
   * 点击处理
   */
  clicks: function (e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/index/foodform/index?id=' + id
    })
  },
  /**
   * 订餐
   */
  dinner(e) {
    const {isCoupon} = this.data
    const { dataset } = e.currentTarget
    const { id, index } = dataset
    const { list } = this.data
    this.store.data.dinner = list[index]
    if (!isCoupon) {
      this.store.data.coupon = {}
    }
    this.update()
    wx.navigateTo({
      url: `/pages/index/foodform/index?id=${id}&isCoupon=${isCoupon}`
    })
  },
  /**
   * 下拉中断
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  /**
   * 上拉
   */
  onReachBottom: function () {
  },
  onShareAppMessage: function (res) {
    // 构造并返回自定义数据
    let session = SessionUtil.getInstanceSync();
    return (new PagePromoter( this.route, { tagId : this.data.tagId }))
    .setShareTitle(session.getTheSellingServerSync().showName)
    .buildShareInfo()
  },
  search(e) {
    const { detail } = e
    this.setData({ pageNo: 1, keywords: detail })
    this.getDinnerList(detail, '')
  },
  filterDinner() {
    this.filter.showView()
  },
  searchHandler(e) {
    this.filter.hideView()
    const { detail } = e
    this.getDinnerList('', detail)
  },
  lower() {
    let { pageNo } = this.data
    this.setData({
      type: 'lower'
    })
    const { keywords } = this.data
    this.getDinnerList(keywords)
  },
  upper() {
    this.setData({
      pageNo: 1,
      type: 'upper'
    })
    const { keywords } = this.data
    this.getDinnerList(keywords)
  },
  changeHandler(e) {
    const { detail } = e
    this.setData({ keywords: detail })
  }
})